package model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

public class IPresenter {
	private Connection con;

	public IPresenter() {
		con = Model.getConnection();
	}

	/**
	 * Returns true if the string is initialized (not null), contains
	 * characters, and is one word
	 * 
	 * @param in
	 *            String to check
	 * @return true if the string is initialized (not null), contains
	 *         characters, and is one word. returns false otherwise
	 */
	protected boolean checkString(String in) {
		boolean out = false;

		if (in != null) {
			if (!in.isEmpty()) {
				if (!in.contains(" ")) {
					out = true;
				}
			}
		}
		return out;
	}
	
	protected boolean checkString2(String in) {
		boolean out = false;

		if (in != null) {
			if (!in.isEmpty()) {
				out = true;
			}
		}
		return out;
	}
	

	protected Statement createStatement() {
		Statement out = null;

		try {
			if(con.isClosed()) {
				con = Model.getConnection();
			}
			
			out = con.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return out;
	}

	protected void closeConnection() {
		try {
			if (con != null)
				con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected int executeSQLUpdate(String command) {
		int out = -1;
		if (command != null) {
			if (!command.isEmpty()) {
				try {
					out = createStatement().executeUpdate(command);
					closeConnection();
				} catch (MySQLIntegrityConstraintViolationException e) {
					System.out.println("Integrity Violation");
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return out;
	}

	protected ResultSet executeSQLQuery(String command) {
		ResultSet out = null;

		if (command != null) {
			if (!command.isEmpty()) {
				try {
					out = createStatement().executeQuery(command);
					//closeConnection();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} // close catch
			} // close empty if
		} // close null if
		return out;
	} // close executeSQLQuery method
	
	protected boolean executeSQLCreate(String command) {
		boolean out = false;
		if (command != null) {
			if (!command.isEmpty()) {
				try {
					out = createStatement().execute(command);
					closeConnection();
				} catch (MySQLIntegrityConstraintViolationException e) {
					System.out.println("Integrity Violation");
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return out;
	}
	
	protected char convertBool(boolean in) {
		if(in) {
			return 'Y';
		}
		else {
			return 'N';
		}
	}
} // close IPresenter
